<template>
  <el-dialog
    title="提示"
    :visible.sync="dialogVisible"
    :before-close="handleClose"
  >
    <div v-loading="isLoading">
      <el-checkbox
        v-for="item in roleList"
        :key="item.role_id"
        v-model="item.isSelected"
        >{{ item.role_name }}</el-checkbox
      >
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="comfire">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
/*
  通过user_id查询所有的角色

  设置用户角色
 */
import { getAllRole } from "@/api/xxl-springboot/role.js";
import { saveManRole } from "@/api/xxl-springboot/user.js";

export default {
  props: {
    status: {
      type: Boolean,
      default: false,
    },
    rowData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      roleList: [],
      isLoading: false,
    };
  },
  watch: {
    rowData: {
      handler(newVal) {
        if (newVal) {
          this.resetData();
          this.getRoleList();
        }
      },
      deep: true,
    },
  },
  computed: {
    dialogVisible: {
      get() {
        return this.status;
      },
      set(val) {
        this.$emit("update:status", val);
      },
    },
  },
  methods: {
    /**
     * 重置弹窗
     */
    resetData() {
      Object.assign(this.$data, this.$options.data());
    },
    /**
     * 获取所有的角色并回填当前用户所有的角色
     */
    async getRoleList() {
      try {
        const roleidArr = this.rowData.userRoleArr.map((val) => {
          return Number(val.role_id);
        });
        this.isLoading = true;
        const { data, code } = await getAllRole();
        if (code == 200) {
          let reslut = data || [];
          reslut.forEach((val) => {
            if (roleidArr.indexOf(val.role_id) > -1) {
              val.isSelected = true;
            } else {
              val.isSelected = false;
            }
          });
          this.roleList = reslut;
        }
        this.isLoading = false;
      } catch (error) {
        this.isLoading = false;
      }
    },
    /**
     * 给用户分配角色
     */
    async comfire() {
      let roleList = this.roleList
        .filter((item) => {
          return item.isSelected;
        })
        .map((val) => {
          return val.role_id;
        });
      let params = {
        user_id: this.rowData.user_id,
        roleList,
      };
      const { code, data } = await saveManRole(params);
      if (code == 200) {
        this.$emit("on-ok");
      }
    },
    /**
     * 点击右上角的关闭按钮
     * @param {*} done 函数控制是否关闭
     */
    handleClose(done) {
      done();
    },
  },
};
</script>
